package com.aurora_manito.xiaomi.Controller.filter;

import com.aurora_manito.xiaomi.entity.User;
import com.aurora_manito.xiaomi.service.UserService;
import com.aurora_manito.xiaomi.utils.Base64Utils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName="AutoLoginFilter",value = "/index.jsp")
public class AutoLoginFilter implements Filter {
    @Autowired
    UserService userService;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest  request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        User checkUser=(User)request.getSession().getAttribute("user");
        if(checkUser!=null){
            //放行
            filterChain.doFilter(request,response);
            return;
        }
        //2.没有登录
        Cookie[] cookies=request.getCookies();
        if(cookies!=null)
        {
            for(Cookie cookie:cookies)
            {
                if(cookie.getName().equals("userInfo")){
                    String value=cookie.getValue();
                    String userinfo=Base64Utils.decode(value);
                    String[] userinfos=userinfo.split("#");
                    //虽说从cookie拿到了用户名密码，但是还是有可能出现用户
                    //更改了密码
                    checkUser.setUsername(userinfos[0]);
                    checkUser.setPassword(userinfos[1]);
                    User user=userService.login(checkUser);
                    if(user!=null)
                    {
                        if(user.getFlag()==1)
                        {
                            request.getSession().setAttribute("user",user);
                            filterChain.doFilter(request,response);
                            return;
                        }
                    }else{
                        //账号密码已经错删除Cookie
                        //将cookie信息写空
                        Cookie cookie1=new Cookie("userinfo","");
                        //设置时间0
                        cookie1.setMaxAge(0);
                        //
                        cookie1.setPath("/");
                        response.addCookie(cookie1);
                    }
                }
            }
        }

        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
